<template>

  <el-tree
    ref="tree"
    :data="allFn"
    show-checkbox
    node-key="id"
    :default-expanded-keys="[2, 3]"
    :default-checked-keys="[5]"
    :props="{label:'name'}"
    @check-change="onCheckChange">
  </el-tree>

</template>

<script>

import axios from '@/util/axios';
import toRecu  from '@/util/recu';

const addDefault = (fns) => {
  for (const fn of fns) {
    if(fn.children && fn.children.length > 0){
      const id = fn.id;
      fn.id = id + '-pnt';
      addDefault(fn.children);
      fn.children.push({
        id,
        name:'默认'
      });
    }
  }
}

let valueTimeout = null;
let isLoad = false;
let isSet = false;
export default {

  mounted(){
    this.load();
  },

  props:{
    value:{
      type:Array,
      default(){
        return [];
      }
    },
    url:{
      type:String
    }
  },

  watch:{
    value(newVal){
      clearTimeout(valueTimeout);
      valueTimeout = setTimeout(e => {
        this._val = newVal || [];
        this.$refs.tree.setCheckedKeys(this._val);
        isSet = true;
      },50);
    }
  },

  data(){
    return {
      allFn:[],
      fns:[],
      _val:[],
      timeout:null,
      __prev_def:false
    }
  },

  methods:{

    load(){
      axios.get(this.url).then(({data}) => {
        this.allFn = toRecu(data,undefined,'uid','pUid');
        addDefault(this.allFn);
        if(isSet){
          this.$refs.tree && this.$refs.tree.setCheckedKeys(this._val||[]);
        }


      });
    },

    onCheckChange(){
      clearTimeout(this.timeout);
      this.timeout = setTimeout(()=>{
        const fns = this.fns = [];
        for (const id of this.$refs.tree.getCheckedKeys()) {
          if(!/\-pnt$/.test(id)){
            fns.push(id);
          }
        }
        this.$emit('input',fns);
      },10);
    }

  }



}

</script>
